package com.liu.springmvc.adapter;

import com.liu.springmvc.annotation.RequestParam;
import com.liu.springmvc.handler.HandlerMethod;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/1/23 15:32
 */
@Component
public class MyAnnotationHandlerAdapter implements HandlerAdapter{

    @Override
    public boolean supports(Object handler) {
        return handler instanceof HandlerMethod;
    }

    @Override
    public Object handler(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        HandlerMethod info = (HandlerMethod) handler;

        Method method = info.getMethod();
        Parameter[] parameters = method.getParameters();

        Object[] param = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            String value = parameters[i].getAnnotation(RequestParam.class).value();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                if (entry.getKey().equals(value)){
                    param[i] = entry.getValue()[0];
                }
            }
        }

        return method.invoke(info.getBean(),param);
    }

}
